package com.apes.framework.util;

import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.event.ApesEvent;
import com.apes.framework.plugin.event.ApesEventMulticaster;
import com.apes.oap.ServiceRouter;
import com.apes.oap.event.OapEvent;
import com.apes.oap.event.RopEventMulticaster;

import java.util.List;

/**
 * 功能：事件工具类
 *
 * @author xul
 * @create 2018-01-11 15:28
 */
public class EventUtil {

    /**
     * 功能：发送事件
     * @param event
     */
    public static void multicastEvent(OapEvent event){
        RopEventMulticaster multicaster = getRopEventMulticaster();
        multicaster.multicastEvent(event);
    }

    private static RopEventMulticaster getRopEventMulticaster() {
        ServiceRouter serviceRouter = RopUtil.getServiceRouter();
        return serviceRouter.getRopContext().getEventMulticaster();
    }


    /**
     * 功能：发送同步事件
     */
    public static List sendSynEvent(Object source, String topic, Object body) {
        ApesEvent event = new ApesEvent(source, topic, true, body);
        multicast(event);
        return event.getResults();
    }

    /**
     * 功能：发送异步事件
     *
     * @param topic
     * @param body
     */
    public static void sendAynEvent(Object source, String topic, Object body) {
        ApesEvent event = new ApesEvent(source, topic, false, body);
        multicast(event);
    }

    /**
     * 功能：发送事件
     */
    private static void multicast(ApesEvent event) {
        ApesEventMulticaster multicaster = getBean(ApesEventMulticaster.class);
        multicaster.multicastEvent(event);
    }

    protected static <T> T getBean(Class<T> clazz) {
        return SpringManager.getBean(clazz);
    }

}
